<%@ page contentType="text/html;charset=utf-8"%>
<%@ page import="com.alibaba.fastjson.*,java.lang.*,java.util.*"%>
<%@ page import="com.frogs.ucenter.dao.*,com.frogs.framework.component.cache.Cache,com.frogs.framework.web.filter.*,com.frogs.ucenter.service.*,com.frogs.framework.util.httpclient.*,com.frogs.ucenter.entity.*"%>
<%@ page import="com.frogs.framework.util.*,com.frogs.system.util.*"%>
<%@include file="/inc/taglibs.jsp"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>同步微信用户信息</title>
<link type="text/css" rel="stylesheet" href="${CSS_PATH}/haoyao.css" />
<link type="text/css" rel="stylesheet" href="${CSS_PATH}/ucenter.css" />
<script type="text/javascript" src="${JS_PATH}/haoyao.js"></script>
<script type="text/javascript" src="${LOCAL_JS_PATH }/lib.js"></script>
<script type="text/javascript" src="${LOCAL_JS_PATH }/hysValidate.js"></script>
</head>

<body>
<%

	final Cache cache = (Cache)SpringWebContext.getSpringContext().getBean("xmemcached");
	final WebApplicationContext context = SpringWebContext.getSpringContext();
	final UserAccountInfoDao userAccountInfoDao = (UserAccountInfoDao)context.getBean("userAccountInfoDao");
	final UserBaseInfoDao userBaseInfoDao = (UserBaseInfoDao)context.getBean("userBaseInfoDao");
	final UserLevelInfoDao userLevelInfoDao = (UserLevelInfoDao)context.getBean("userLevelInfoDao");
	final UserOpenPlatformInfoDao userOpenPlatformInfoDao = (UserOpenPlatformInfoDao)context.getBean("userOpenPlatformInfoDao");
	final WechatUserPhoneDao wechatUserPhoneDao = (WechatUserPhoneDao)context.getBean("wechatUserPhoneDao");
	final WechatUserBaseInfoDao wechatUserBaseInfoDao = (WechatUserBaseInfoDao)context.getBean("wechatUserBaseInfoDao");
	
	final String[] proxyIps= {"120.4.202.18:8888","182.88.178.31:9999","222.83.14.145:3128",
						"14.218.85.99:9999","218.107.50.51:9999","122.143.3.75:81",
						"61.161.175.91:8080","218.22.21.249:80","221.192.236.205:80",
						"183.203.22.100:80","124.115.211.30:9999","124.72.94.149:83",
						"14.218.85.99:9999","124.231.136.107:8080"};
	
	int tmpCountPage = 0;
	int tmpCurPage = 0;
	int tmpShutdown = 1;
	if(null != cache.get("countPage")) {
		tmpCountPage = Integer.parseInt(String.valueOf(cache.get("countPage")));
	}
	if(null != cache.get("curPage")){
		tmpCurPage = Integer.parseInt(String.valueOf(cache.get("curPage")));
	}
	if(null != cache.get("shutdown")) {
		tmpShutdown = Integer.parseInt(String.valueOf(cache.get("shutdown")));
		System.out.println("运行状态：" + (tmpShutdown==0?"运行中":"停止"));
	}
	if(tmpShutdown != 1) {
		out.println("已有线程在跑数据,当前页数：" + tmpCurPage + ",总页数：" + tmpCountPage);
		return;
	}
	
	class NewThread extends Thread{
		
			int curPage = 0;
			int countPage = 0;
			int shutdown = 0;
			public NewThread( int curPage, int countPage, int shutdown){
				this.curPage = curPage;
				this.countPage = countPage;
				this.shutdown = shutdown;
			}

			@Override
			public void run() {
				// TODO Auto-generated method stub
			boolean lastPage = false;
			int errCount = 0;
				do {
					curPage++;
					Map<String, String> headMap = new HashMap<String, String>();
					headMap.put("User-Agent",
							"Mozilla/4.0 (compatible; MSIE 7.0;)");
					headMap.put(
							"Accept",
							"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*");
					headMap.put("Bizmp-Version", "1.0");
					// String ipPort = pingProxy(proxyIps);
					// System.out.println(ipPort);
					/*
					 * if(StringUtil.isEmpty(ipPort)) {
					 * System.out.println("无可用代理IP"); return; }
					 */

					PostObject po = new PostObject();
					po.setCharset("UTF-8");
					po.setContent("method=jsonUserGoodLoad");
					po.setContentType(ContentTypeEnum.WWW_FORM.toString());
					po.setHeaders(headMap);
					// po.setProxyIpAndPort(ipPort.split(":"));
					po.setHttps(false);
					// po.setUrl("http://api.uc.frogshealth.com/v1/user/list.jsonp?uuid=mall&token=mall_2014&phone=13450362589");
					po.setUrl("http://w.frogshealth.com/haoyao/wxPayPortApi.do?method=sreach&bingPhone=2&pageNo="
							+ curPage);
					Object resultObject = HttpClientUtil.post(po);
					try {
						JSONObject json = JSONObject
								.parseObject((String) resultObject);

						countPage = json.getJSONObject("pagination")
								.getIntValue("totalPage");
						lastPage = json.getJSONObject("pagination")
								.getBooleanValue("lastPage");
						System.out.println("curPage==" + curPage);
						cache.put("curPage", curPage);
						cache.put("shutdown", 0);
						cache.put("countPage", countPage);

						/******************************* 以上为获取数据操作 ****************************/

						/********************************* 华丽的分界线 ******************************/

						/******************************* 以下为保存数据操作 ****************************/

						JSONArray jsr = json.getJSONObject("pagination")
								.getJSONArray("list");
						for (int ind = 0; ind < jsr.size(); ind++) {
							JSONObject wec = jsr.getJSONObject(ind);
							String phone = wec.getString("bingPhone");
							String openId = wec.getString("openId");
							Integer wechatApplicablePlatformId = 3;
							Integer applicablePlatformId = 3;
							String expandCode = "";
							System.out.println("phone=" + phone + ",openId="
									+ openId);
							Map<String, Object> params = new HashMap<String, Object>();
							params.put("eqBingPhone", phone);
							params.put("eqWechatApplicationId",
									wechatApplicablePlatformId);
							int count = wechatUserBaseInfoDao
									.selectCountByMap(params);
							if (count > 0) {
								System.out.println("<br/>手机号码：" + phone + "已经绑定过官网用户");
								continue;
							}

							params.clear();
							params.put("eqPhone", phone);
							params.put("eqIsPhoneValid",
									UserAccountInfoStatusEnum.AVAILABILITY_YES
											.getId());
							PageList<UserAccountInfo> userAccountInfos = userAccountInfoDao
									.selectByMap(params, false);
							UserAccountInfo userAccountInfo = new UserAccountInfo();
							String messageContent = "";
							if (userAccountInfos != null
									&& userAccountInfos.size() > 0) {
								userAccountInfo = userAccountInfos.get(0);
								int userId = userAccountInfo.getId();
								params.clear();
								params.put("eqUserId", userId);
								params.put("eqWechatApplicationId",
										wechatApplicablePlatformId);
								count = wechatUserBaseInfoDao
										.selectCountByMap(params);
								if (count > 0) {
									System.out.println("<br/>手机号码：" + phone
											+ "已经绑定过官网用户");
									continue;
								}
							} else {
								String accountName = "";
								/**
								 * 生成用户名
								 */
								{
									String pre = "ehy";
									boolean flag = false;
									Map<String, Object> param = new HashMap<String, Object>();
									count = 0;
									do {
										accountName = pre + RandomString(7);
										param.put("eqAccountName", accountName);
										count = userAccountInfoDao
												.selectCountByMap(param);
										if (count > 0) {
											flag = false;
										} else {
											flag = true;
										}
									} while (!flag);
								}
								String passwd = "";

								/**
								 * 生成随机密码
								 */
								{
									int[] array = { 0, 1, 2, 3, 4, 5, 6, 7, 8,
											9 };
									Random rand = new Random();
									for (int i = 10; i > 1; i--) {
										int index = rand.nextInt(i);
										int tmp = array[index];
										array[index] = array[i - 1];
										array[i - 1] = tmp;
									}
									String result = "";
									for (int i = 0; i < 6; i++)
										result = result + array[i];
									passwd = String.valueOf(result);
								}

								/**
								 * 代码块：新增用户
								 */
								String email = "";
								{
									userAccountInfo.setAccountName(accountName);
									userAccountInfo.setEmail(email);
									if (!StringUtil.isEmpty(email)) {
										userAccountInfo
												.setIsEmailValid(UserAccountInfoStatusEnum.AVAILABILITY_YES
														.getId());
									}
									userAccountInfo.setPhone(phone);
									if (!StringUtil.isEmpty(phone)) {
										userAccountInfo
												.setIsPhoneValid(UserAccountInfoStatusEnum.AVAILABILITY_YES
														.getId());
									}
									userAccountInfo
											.setApplicablePlatformId(applicablePlatformId);
									userAccountInfo.setExpandCode(expandCode);
									if (!StringUtil.isEmpty(passwd)) {
										userAccountInfo.setPasswd(StringUtil
												.md5(passwd));
									}
									userAccountInfo
											.setIsAccountValid(UserAccountInfoStatusEnum.AVAILABILITY_YES
													.getId());
									userAccountInfo
											.setIsAccountActive(UserAccountInfoStatusEnum.STATUS_NORMAL
													.getId());
									Date date = new Date();
									userAccountInfo.setCreateTime(date
											.getTime());
									userAccountInfoDao.insert(userAccountInfo);
								}

								/**
								 * 代码块： 初始化用户
								 */
								{
									String nickname = "";
									UserBaseInfo userBaseInfo = new UserBaseInfo();
									UserLevelInfo userLevelInfo = new UserLevelInfo();
									userBaseInfo.setId(userAccountInfo.getId());
									userBaseInfo
											.setUserType(UserTypeEnum.GENERAL
													.getType());
									// TODO 默认的一个昵称
									if (StringUtil.isEmpty(nickname)) {
										userBaseInfo
												.setNickName(userAccountInfo
														.getAccountName());
									} else {
										userBaseInfo.setNickName(nickname);
									}
									if (!StringUtil.isEmpty(userAccountInfo
											.getPhone())) {
										JSONArray jsonArray = new JSONArray();
										JSONObject jsonObject = new JSONObject();
										jsonObject.put("isVerify", 1);
										jsonObject.put("phone",
												userAccountInfo.getPhone());
										jsonObject.put("isImport", 0);
										jsonArray.add(jsonObject);
										userBaseInfo.setOrderPhone(jsonArray
												.toJSONString());
									}
									userLevelInfo.setId(userAccountInfo.getId());
									userBaseInfoDao.insert(userBaseInfo);
									userLevelInfoDao.insert(userLevelInfo);

								}
							}
							/**
							 * 代码块： 绑定官网用户和微信用户关系
							 */
							{
								UserOpenPlatformInfo userOpenPlatformInfo = new UserOpenPlatformInfo();
								userOpenPlatformInfo.setOpenId(openId);
								userOpenPlatformInfo
										.setOpenPlatformId(applicablePlatformId);
								userOpenPlatformInfo.setUserId(userAccountInfo
										.getId());
								userOpenPlatformInfoDao
										.insert(userOpenPlatformInfo);
							}
							/**
							 * 代码块： 更新微信用户信息
							 */
							{
								params = new HashMap<String, Object>();
								params.put("eqOpenId", openId);
								WechatUserBaseInfo wechatUserBaseInfo = new WechatUserBaseInfo();
								{
									wechatUserBaseInfo.setAddrearea(wec.getString("addrearea"));
									wechatUserBaseInfo.setBingPhone(wec.getString("bingPhone"));
									wechatUserBaseInfo.setCity(wec.getString("city"));
									wechatUserBaseInfo.setCountry(wec.getString("contry"));
									wechatUserBaseInfo.setCreateTime(wec.getString("createTime"));
									wechatUserBaseInfo.setHeadImgUrl(wec.getString("headImgUrl"));
									wechatUserBaseInfo.setLanguage(wec.getString("language"));
									wechatUserBaseInfo.setNickName(wec.getString("nickName"));
									wechatUserBaseInfo.setOpenId(wec.getString("openId"));
									wechatUserBaseInfo.setProvince(wec.getString("province"));
									wechatUserBaseInfo.setReceiveArea(wec.getString("receiveArea"));
									wechatUserBaseInfo.setReceiveCity(wec.getString("receiveCity"));
									wechatUserBaseInfo.setReceiveDetailInfo(wec.getString("receiveDetailInfo"));
									wechatUserBaseInfo.setReceiveProvince(wec.getString("receiveProvince"));
									wechatUserBaseInfo.setReceiver(wec.getString("receiver"));
									wechatUserBaseInfo.setReceiveTel(wec.getString("receiveTel"));
									wechatUserBaseInfo.setReceiveZipcode(wec.getString("receiveZipcode"));
									wechatUserBaseInfo.setSex(wec.getInteger("sex"));
									wechatUserBaseInfo.setSubScribe("1".equalsIgnoreCase(wec.getString("subScribe"))?1:0);
									wechatUserBaseInfo.setSubscribeTime(wec.getString("subscribeTime"));
									wechatUserBaseInfo.setUnsubscribeTime(wec.getString("unsubscribeTime"));
									wechatUserBaseInfo.setUpdateTime(wec.getString("updateTime"));
									wechatUserBaseInfo.setUserName(wec.getString("userName"));
									wechatUserBaseInfo.setUyuyUserid(wec.getString("uyuyUserId"));
									wechatUserBaseInfo.setWxuserId(wec.getInteger("id"));
									wechatUserBaseInfo.setX(wec.getString("x"));
									wechatUserBaseInfo.setY(wec.getString("y"));
								}
								PageList<WechatUserBaseInfo> userBaseInfos = wechatUserBaseInfoDao
										.selectByMap(params, false);
								if (userBaseInfos != null
										&& userBaseInfos.size() > 0) {
									WechatUserBaseInfo tmpWechatUserBaseInfo = userBaseInfos.get(0);
									wechatUserBaseInfo.setId(tmpWechatUserBaseInfo.getId());
									wechatUserBaseInfo.setBingPhone(phone);
									wechatUserBaseInfo
											.setUserId(userAccountInfo.getId());
									wechatUserBaseInfo
											.setUserName(userAccountInfo
													.getAccountName());
									wechatUserBaseInfo
											.setWechatApplicationId(wechatApplicablePlatformId);
									wechatUserBaseInfoDao
											.update(wechatUserBaseInfo);
								} else {
									wechatUserBaseInfo.setBingPhone(phone);
									wechatUserBaseInfo
											.setUserId(userAccountInfo.getId());
									wechatUserBaseInfo
											.setUserName(userAccountInfo
													.getAccountName());
									wechatUserBaseInfo.setOpenId(openId);
									wechatUserBaseInfo
											.setWechatApplicationId(wechatApplicablePlatformId);
									wechatUserBaseInfoDao
											.insert(wechatUserBaseInfo);
								}
							}

							/**
							 * 代码块：新增微信用户手机绑定关系
							 */
							{
								Map<String, Object> param = new HashMap<String, Object>();
								param.put("eqOpenId", openId);
								param.put("eqPhone", phone);
								count = wechatUserPhoneDao
										.selectCountByMap(param);
								if (count < 1) {
									WechatUserPhone wechatUserPhone = new WechatUserPhone();
									wechatUserPhone.setOpenId(openId);
									wechatUserPhone.setPhone(phone);
									wechatUserPhoneDao.insert(wechatUserPhone);
								}
							}
							
							///调用为微信商城接口，通知商城用户绑定结果
							
						}
						errCount = 0;
						System.out.println("保存第" + curPage + "页");
					} catch (Exception e) {
						e.printStackTrace();
						errCount++;
						curPage--;
						cache.put("curPage", curPage);
						System.out.println("<br/>获取数据出错,重试次数" + errCount);
						if (errCount > 10) {
							cache.put("shutdown", 1);
							return;
						}
					}
				} while (countPage > 0 && curPage < countPage && !lastPage);
				cache.remove("curPage");
				cache.remove("shutdown");
				System.out.println("finish");
				System.out.println(result());
			}
		}
		new NewThread( tmpCurPage, tmpCountPage, tmpShutdown).start();
%>

<%!
	String RandomString(int length) {
		String str = "0123456789";
		Random random = new Random();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int num = random.nextInt(10);
			buf.append(str.charAt(num));
		}
		return buf.toString();
	}
 %>
<%!
	String pingProxy(String[] proxyIps) {
		for(String ip : proxyIps){
        	if(!StringUtil.isEmpty(ip)) {
        		break;
        	}
        	return "";
        }
        
		int index = (new Random()).nextInt(proxyIps.length);
        String ipPort = proxyIps[index];
        
        if(StringUtil.isEmpty(ipPort)) {
        	pingProxy(proxyIps);
        }
        
        Socket socket = new Socket();
        String[] ipPortResult = ipPort.split(":");
        String host = ipPortResult[0];
        int port = Integer.valueOf(ipPortResult[1]);
        InetSocketAddress address = new InetSocketAddress(host, port);
        try {
            socket.connect(address, 10 * 1000);
            if (!socket.isConnected()) {
            	System.out.println(ipPort + "不可用");
            	proxyIps[index]="";
                pingProxy(proxyIps);
            } else {
                socket.close();
            }
        } catch (Exception e) {
        	System.out.println(">>>>>" + index);
            e.printStackTrace();
            proxyIps[index]="";
            pingProxy(proxyIps);
        }
        return ipPort;     
    }
 %>
 
 <%!
 	boolean result(){
 		return true;
 	} 
 %>
</body>
</html>